//
//  JSBridgeManager.m
//  JSBridgeDemo
//
//  Created by zhang_rongwu on 16/3/1.
//  Copyright © 2016年 zhang_rongwu. All rights reserved.
//

#import "JSBridgeManager.h"
#import "ICHeaderFile.h"

#define kTGJSBridgeProtocolScheme @"icom"
#define kTGJSBridgeNotificationSeparator @"-"
#define kTGJSBridgeNotificationReady @"NotificationReady"
#define iCGJSBridgePostNotification @"iCGJSBridgePostNotification"
@interface JSBridgeManager ()

@end

@implementation JSBridgeManager
+ (id)jsBridgeWithDelegate:(id <JSBridgeManagerDelegate>)delegate
{
    JSBridgeManager* bridge = [[JSBridgeManager alloc] init];
    bridge.delegate = delegate;
    return bridge;
}

- (id)init
{
    if(self = [super init]) {
        self.infoList = [[NSMutableDictionary alloc]init];
    }
    return self;
}

- (void)dispatchNotification:(NSString*)notificationString
                 fromWebView:(WKWebView*)webView {
    // 收到处理消息
    NSDictionary *responseDict = [self fetchNotificationWithStr:notificationString fromWebView:webView];
    if([self.delegate respondsToSelector:@selector(jsBridge:didReceivedNotiDict:Notification:fromWebView:)]) {
        [self.delegate jsBridge:self didReceivedNotiDict:responseDict Notification:notificationString fromWebView:webView];
    }
}

/**
 *  收到html的js请求后对数据进行处理
 *
 */
- (NSDictionary*)fetchNotificationWithStr:(NSString*)notificationString
                              fromWebView:(WKWebView*)webView {
    NSDictionary *responseDict = [NSDictionary initWithJsonString:notificationString];
    return responseDict;
}

- (void)postNotificationJavaScript:(NSString *)javaScript
                         toWebView:(WKWebView *)webView {
    [webView evaluateJavaScript:javaScript completionHandler:^(NSString *message, NSError * _Nullable error) {
        NSLog(@"js回调信息 error ： %@", error);
    }];
}

#pragma mark - WKNavigationDelegate

/**
 *  页面开始加载时调用
 *
 *  @param webView    实现该代理的webview
 *  @param navigation 当前navigation
 */
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    
    NSLog(@"%s -- %@", __FUNCTION__, webView.URL);
}

/**
 *  当内容开始返回时调用
 *
 *  @param webView    实现该代理的webview
 *  @param navigation 当前navigation
 */
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
    NSLog(@"%s", __FUNCTION__);
    NSLog(@"%s -- %@", __FUNCTION__, navigation);
}

/**
 *  页面加载完成之后调用
 *
 *  @param webView    实现该代理的webview
 *  @param navigation 当前navigation
 */
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    NSLog(@"%s", __FUNCTION__);
    NSLog(@"%s -- %@", __FUNCTION__, navigation);
}

/**
 *  加载失败时调用
 *
 *  @param webView    实现该代理的webview
 *  @param navigation 当前navigation
 *  @param error      错误
 */
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    if ([self.delegate respondsToSelector:@selector(jsBridge:didFailProvisionalNavigation:withError:)]) {
        [self.delegate jsBridge:self didFailProvisionalNavigation:navigation withError:error];
    }
    
    NSLog(@"%s", __FUNCTION__);
    NSLog(@"%s -- %@", __FUNCTION__, navigation);
}

/**
 *  接收到服务器跳转请求之后调用
 *
 *  @param webView      实现该代理的webview
 *  @param navigation   当前navigation
 */
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation {
    NSLog(@"%s", __FUNCTION__);
    NSLog(@"%s -- %@", __FUNCTION__, navigation);
}

/**
 *  在收到响应后，决定是否跳转
 *
 *  @param webView            实现该代理的webview
 *  @param navigationResponse 当前navigation
 *  @param decisionHandler    是否跳转block
 */
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
    // 允许跳转
    decisionHandler(WKNavigationResponsePolicyAllow);
    return;
}

/**
 *  在发送请求之前，决定是否跳转
 *
 *  @param webView          实现该代理的webview
 *  @param navigationAction 当前navigation
 *  @param decisionHandler  是否调转block
 */

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    
    NSDictionary *referDict = [[NSUserDefaults standardUserDefaults] objectForKey:@"loadUrlWithRefer"];
    
    if (![ICTools isObjEmpty:referDict]) {
        NSString *url = referDict[@"url"];
        NSString *refer = referDict[@"refer"];
        NSDictionary *headers = [navigationAction.request allHTTPHeaderFields];
        NSString * referer = [headers objectForKey:@"Referer"];
        BOOL isRightReferer = [referer isEqualToString:refer];
        if (isRightReferer) {
            decisionHandler(WKNavigationActionPolicyAllow);
        } else {
            decisionHandler(WKNavigationActionPolicyCancel);
            
            if ([url isEqualToString:[navigationAction.request.URL absoluteString]]) {
                NSMutableDictionary * muDict = [[NSMutableDictionary alloc] initWithDictionary:headers];
                [muDict setObject:refer forKey:@"Referer"];
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                    dispatch_async(dispatch_get_main_queue(), ^{
                        NSURL *url = [navigationAction.request URL];
                        NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60.0];
                        request.allHTTPHeaderFields = muDict;
                        [webView loadRequest:request];
                    });
                });
            }
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"loadUrlWithRefer"];// 使用完成后移除
        }
    } else {
        NSURL *url = navigationAction.request.URL;
        NSString *scheme = [url scheme];
        if ([scheme isEqualToString:kTGJSBridgeProtocolScheme]) {
            [self dispatchNotification:[url absoluteString] fromWebView:webView];
        }  else {
            //forward
            if (![scheme isEqualToString:@"https"] && ![scheme isEqualToString:@"http"]) {
                [[UIApplication sharedApplication] openURL:url];
            }
        }
        decisionHandler(WKNavigationActionPolicyAllow);
    }
}

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    NSLog(@"%@", message.name);
}

@end
